package qc.gateway.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.utils.DateUtil;
import qc.gateway.entity.QcBlackList;
import qc.gateway.repository.QcBlackListRepository;

import java.util.Date;
import java.util.List;

/**
 * Gateway中用于获取黑名单集合和验证是否在黑名单中
 *
 * @author QuCheng Tech
 * @since 2025/1/11
 */
@Service
public class QcBlackListService {
    private QcBlackListRepository repository;

    @Autowired
    public void setQcBlackListRepository(QcBlackListRepository repository) {
        this.repository = repository;
    }

    /***
     * 获取所有当前时间有效的黑名单集合
     *
     * @return java.util.List<qc.gateway.entity.QcBlackList>
     * @author QuCheng Tech
     * @since 2025/1/11
     */
    public List<QcBlackList> getNowValids() {
        Date now = DateUtil.getNowDate();

        LambdaQueryWrapper<QcBlackList> wrapper = new LambdaQueryWrapper<>();
        //and tm<=now and (expiredtm is null or expiredtm >=now)
        wrapper.lt(QcBlackList::getTm, now);
        wrapper.and(q -> q.isNull(QcBlackList::getExpiredtm).or().gt(QcBlackList::getExpiredtm, now));

        return repository.selectList(wrapper);
    }

    /***
     * 将指定ID的黑名单命中次数加1
     *
     * @param id 黑名单记录ID
     * @return void
     * @author QuCheng Tech
     * @since 2025/2/3
     */
    public void addHitCounts(int id) {
        LambdaUpdateWrapper<QcBlackList> wrapper = new LambdaUpdateWrapper<>();

        wrapper.setSql("`HITCOUNT`=`HITCOUNT`+1");
        wrapper.set(QcBlackList::getHittm, DateUtil.getNowDate());

        wrapper.eq(QcBlackList::getId, id);

        repository.update(null, wrapper);
    }
}
